package com.jmes.web.dao;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.log4j.Logger;

import java.io.IOException;
import java.io.Reader;

/**
 * 数据库的访问管理类
 * User: jinshunlong
 * Date: 13-4-13
 * Time: 下午9:17
 */
public class DaoManager {
    private static Logger logger = Logger.getLogger(DaoManager.class);
    private static SqlSessionFactory factory;
    static {
        Reader reder = null;
        try {
            reder = Resources.getResourceAsReader("mybatis-config.xml");
        } catch (IOException e) {
            logger.error(e.getMessage(),e);
        }
        factory = new SqlSessionFactoryBuilder().build(reder);
    }


    public static interface ExecDAO{
        public Object execDao(SqlSession sqlSession);
    }

    public static Object execDao(ExecDAO execDAO){
        SqlSession sqlSession = null;
        Object re = null;
        try{
            sqlSession = factory.openSession(true);
            re = execDAO.execDao(sqlSession);
        }catch (Exception e){
            logger.error(e.getMessage(),e);
        }finally {
            if(sqlSession != null){
                sqlSession.close();
            }
        }
        return re;
    }
    public static Object execDao(ExecDAO execDAO,boolean autoCommit){
        SqlSession sqlSession = null;
        Object re = null;
        try{
            sqlSession = factory.openSession(autoCommit);
            re = execDAO.execDao(sqlSession);
        }catch (Exception e){
            logger.error(e.getMessage(),e);
        }finally {
            if(sqlSession != null){
                if(!autoCommit){
                    sqlSession.commit(true);
                }
                sqlSession.close();
            }
        }
        return re;
    }

}
